//
//  oldVoiceManager.m
//  laonianbang
//
//  Created by 勇拓 李 on 17/10/18.
//  Copyright © 2017年 zaiyou. All rights reserved.
//

#import "oldVoiceManager.h"
#import "lame.h"
#import "QNuploader.h"
#import "oldNetWork.h"
#import "oldVoiceManager.h"

@interface oldVoiceManager()
{
    dispatch_queue_t _queue;
}
@property (nonatomic, strong)NSFileManager *fileManager;
@end

static char * queueName = "old_voice_queue";

NSString *const voiceDocument = @"voiceDocument";
NSString *const kRecordAudioFile = @"old_record.caf";

#define RECORD_old @"oldRecord.mp3"

@implementation oldVoiceManager

+ ( instancetype ) shareInstance
{
    static oldVoiceManager * instance = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once( &onceToken, ^
                  {
                      instance = [self new];
                  });
    return instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _queue = dispatch_queue_create(queueName, DISPATCH_QUEUE_CONCURRENT);
    }
    
    return self;
}

- (NSFileManager *)fileManager
{
    if (!_fileManager) {
        _fileManager = [NSFileManager defaultManager];
    }
    
    return _fileManager;
}


- (void)getVoiceUrl:(NSString *)url block:(VoiceBlock)block
{
    NSString *pathUrl = nil;
    
    NSArray *array = [url componentsSeparatedByString:@"/"];
    
//    NSString *newUrl = [NSString stringWithFormat:@"http://oy673naa2.bkt.clouddn.com/%@", url];
    
    NSString *newUrl = [array lastObject];
    
    pathUrl = [self getfileUrl:newUrl];
    
    if (pathUrl) {
        block(pathUrl);
    }
    else
    {
        [OLDNetWork downloadFile:url filePath:[[self getDirectory] stringByAppendingFormat:@"/%@.mp3",newUrl] block:^(NSString *newurl) {
            block(newurl);
        }];
    }
    
}

- (NSString *)getfileUrl:(NSString *)url {
    
    NSString *logFilePath = [[self getDirectory] stringByAppendingFormat:@"/%@.mp3",url];
    
    if (![self.fileManager fileExistsAtPath:logFilePath]) {
        return nil;
    }
    
    return logFilePath;
}

// 创建文件夹
- (NSString *)getDirectory {
    //将NSlog打印信息保存到Document目录下的Log文件夹下
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *logDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:voiceDocument];
    
    BOOL fileExists = [self.fileManager fileExistsAtPath:logDirectory];
    if (!fileExists) {
        NSError *error;
        [self.fileManager createDirectoryAtPath:logDirectory  withIntermediateDirectories:YES attributes:nil error:&error];
        NSLog(@"%@",error);
    }
    
    return logDirectory;
}

#pragma mark - 语音
/**
 *  取得录音文件保存路径
 *
 *  @return 录音文件路径
 */
- (NSString *)getSavePath{
    NSString *urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    urlStr = [urlStr stringByAppendingPathComponent:kRecordAudioFile];
    
//    NSLog(@"file path:%@",urlStr);
    NSURL *url=[NSURL fileURLWithPath:urlStr];
    return [url absoluteString];
}

- (NSString *)changeCafToMp3
{
    NSString *urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *urlCaf = [urlStr stringByAppendingPathComponent:kRecordAudioFile];
    
    NSString *accountUrl = RECORD_old;
    
    NSString *urlMp3 = [urlStr stringByAppendingPathComponent:accountUrl];
    
    NSString *cafFilePath = urlCaf;    //caf文件路径
    
    NSString *mp3FilePath = urlMp3;//存储mp3文件的路径
    
    NSFileManager* fileManager = [NSFileManager defaultManager];
    
    if([fileManager removeItemAtPath:mp3FilePath error:nil])
        
    {
        
        NSLog(@"删除");
        
    }
    
    
    
    @try {
        
        int read, write;
        
        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置
        
        if(pcm == NULL)
            
        {
            
            NSLog(@"file not found");
            
        }
        
        else
            
        {
            
            fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
            
            FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output 输出生成的Mp3文件位置
            
            
            
            const int PCM_SIZE = 8192;
            
            const int MP3_SIZE = 8192;
            
            short int pcm_buffer[PCM_SIZE*2];
            
            unsigned char mp3_buffer[MP3_SIZE];
            
            
            
            lame_t lame = lame_init();
            
            lame_set_num_channels(lame,1);//设置1为单通道，默认为2双通道
            
            lame_set_in_samplerate(lame, 8000.0);//11025.0
            
            //lame_set_VBR(lame, vbr_default);
            
            lame_set_brate(lame,8);
            
            lame_set_mode(lame,3);
            
            lame_set_quality(lame,2); /* 2=high 5 = medium 7=low 音质*/
            
            lame_init_params(lame);
            
            
            
            do {
                
                read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
                
                if (read == 0)
                    
                    write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
                
                else
                    
                    write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
                
                
                
                fwrite(mp3_buffer, write, 1, mp3);
                
                
                
            } while (read != 0);
            
            
            
            lame_close(lame);
            
            fclose(mp3);
            
            fclose(pcm);
            
            return mp3FilePath;
            
        }
        
        return nil;
        
    }
    
    @catch (NSException *exception) {
        
        NSLog(@"%@",[exception description]);
        
        return nil;
        
    }
    
    @finally {
        
        NSLog(@"执行完成");
        
    }
}


@end
